import validate from 'wechat-validate'
Page({
  // 通过 behaviors 注入 validate 方法
  behaviors: [validate],
  data: {
    nowTime: Date.now(),
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseId: '',
    houseInfo: '',
    houseList: [],
    gender: '1',
    name: '',
    nothingList: [
      {
        name: '暂无可报修房屋',
        disabled: true,
      },
    ],
    mobile: '',
    visitDate: '',
  },

  // 校验规则
  rules: {
    // 房屋信息
    houseInfo: [
      {
        required: true,
        message: '请选择需要访问房屋!',
      },
    ],
    name: [
      {
        required: true,
        message: '请填写房客姓名!',
      },
      {
        pattern: /^[^0-9\s]+$/,
        message: '姓名中不能出现数字',
      },
    ],
    // 手机号
    mobile: [
      {
        required: true,
        message: '当前手机号不能为空!',
      },
      {
        pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
        message: '请检查手机号码是否正确!',
      },
    ],
    // 日期
    visitDate: [
      {
        required: true,
        message: '请选择访问日期',
      },
    ],
  },

  openHouseLayer() {
    this.setData({
      houseLayerVisible: true,
    })
  },
  closeHouseLayer() {
    this.setData({
      houseLayerVisible: false,
    })
  },
  openDateLayer() {
    this.setData({
      dateLayerVisible: true,
    })
  },
  closeDateLayer() {
    this.setData({
      dateLayerVisible: false,
    })
  },
  async goPassport() {
    const isAllValid = this.validate()
    if (!isAllValid) return

    await wx.http.post('/visitor', {
      houseId: this.data.houseId,
      name: this.data.name,
      gender: this.data.gender - 0,
      mobile: this.data.mobile,
      visitDate: this.data.visitDate,
    })
    wx.utils.toast('新增房客成功')
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index',
    })
  },

  async onLoad() {
    /* 获取通过审核的房屋信息 */
    const { data } = await wx.http.get('/house')
    this.setData({ houseList: data })
  },

  /* 选择房屋 */
  onSelect(e) {
    this.setData({
      houseId: e.detail.id,
      houseInfo: e.detail.name,
    })
  },

  /* 确认时间 */
  confirmTime(e) {
    /* 关闭弹层 */
    this.closeDateLayer()
    /* 格式化时间 */
    const visitDate = getApp().formatDate(new Date(e.detail))
    /* 设置访问日期 */
    this.setData({
      visitDate,
    })
  },
  /* 选择性别 */
  confirmGender(e) {
    this.setData({
      gender: e.detail,
    })
  },
})
